package com.sm.imlibrary.http;

import androidx.annotation.NonNull;

import com.scorpio.baselibrary.PoorApplication;
import com.scorpio.baselibrary.utils.DeviceIdUtil;
import com.sm.imlibrary.Constants;
import com.sm.imlibrary.nio.SocketIoManage;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * created by zhud on 2019/8/14
 */
public class IMHttpUtil {
    public static IMHttpApi postString(@NonNull final String jsonString) {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(12, TimeUnit.SECONDS)
                .readTimeout(12, TimeUnit.SECONDS)
                .writeTimeout(12, TimeUnit.SECONDS)
                .addInterceptor(new Interceptor() {
                    @Override
                    public Response intercept(Chain chain) throws IOException {
                        Request.Builder builder = chain.request().newBuilder()
                                .header("uniqueId", DeviceIdUtil.getDeviceId(PoorApplication.getInstance()))
                                .addHeader("accountToken", SocketIoManage.getInstance().getIdentifying())
                                .addHeader("Content-Type", "application/json;charset=UTF-8")
                                .post(RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), jsonString));
                        return chain.proceed(builder.build());
                    }
                })
                .build();
        Retrofit retrofit = new Retrofit.Builder()
                //设置网络请求的Url地址
                .baseUrl(Constants.HTTP_HOST)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                //设置数据解析器
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
        return retrofit.create(IMHttpApi.class);
    }
}
